<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="nickname">
        <el-input v-model="queryParams.nickname" placeholder="请输入用户名" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="手机号" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入手机号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      
      <el-form-item label="运动时间" prop="trainTime">
        <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始时间" end-placeholder="结束时间"></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['mobile:userprescription:add']">新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['mobile:userprescription:remove']">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" height="800" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" v-if="false" />
      <el-table-column fixed label="用户名" align="center" prop="nickname" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="周次" align="center" prop="week" >
        <template #default="scope2">
          <span>第{{ scope2.row.week }}周</span>
        </template>
      </el-table-column>
      <el-table-column label="推荐训练时间" align="center" prop="trainTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.trainTime, '{y}-{m}-{d}') }} 至 {{ parseTime(scope.row.trainTimeEnd, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="课程标题" align="center" prop="title" >
        <template #default="scope3">
          <el-row v-for="(item, index) in scope3.row.titles" style="margin-bottom:5px;">
            <vue-text :value="item" row="5" />
          </el-row>
      </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="text" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['mobile:record:edit']">修改
          </el-button>
          <el-button type="text" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['mobile:record:remove']">删除
          </el-button>
          <el-button type="text" icon="Edit" @click="handleCheckinList(scope.row)" v-hasPermi="['mobile:chckin:list']">打卡明细
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改推荐课程记录对话框 -->
    <el-dialog :title="title" v-model="open"  :width="dialogWidth"  append-to-body>
      <el-form ref="recordRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择用户" filterable remote reserve-keyword :remote-method="remoteMethod"  :loading="loading" clearable style="width: 240px">
            <el-option v-for="dict in userList" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="周次" prop="week">
          <el-input v-model="form.week" placeholder="请输入术后周次" type="number" style="width: 240px"/>
        </el-form-item>
        <el-form-item label="开始训练时间" prop="trainTime">
          <el-date-picker clearable v-model="form.trainTime"  style="width: 240px" type="date" value-format="YYYY-MM-DD"
                          placeholder="请选择开始训练时间">
          </el-date-picker>
        </el-form-item>


        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="类型" @change="changetype($event)" clearable style="width: 240px">
            <el-option key="1" label="标准处方" value="1" />
            <el-option key="2" label="指定分数处方" value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="指定周次" v-model="showweek" v-if="showweek==true" prop="weekType">
          <el-select v-model="form.weekType" placeholder="请选择指定周次处方" @change="changeweek($event)" clearable style="width: 240px">
            <el-option v-for="dict in weekList" :key="dict.value" :label="dict.label" :value="dict.value" />

          </el-select>
        </el-form-item>

        <el-form-item label="指定分数" v-model="showpoint" v-if="showpoint==true" prop="point">
          <el-select v-model="form.pointId" placeholder="请选择指定分数处方" @change="changepoint($event)" clearable style="width: 240px">
            <el-option v-for="dict in pointList" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="课程" v-model="showlesson" v-if="showlesson==true" prop="lessonId">
          <el-row style="margin-bottom: 50px;" v-for="(item, index) in form.lessonPart" >
            <el-input type="hidden" v-model="item.id"/>
            <el-form-item label="标题">
              <el-row style="width: 100%;"><el-input v-model="item.title" style="margin-bottom: 5px; width: 80%;" placeholder="请输入一级标题" readonly="true"/></el-row>
            </el-form-item>

            <el-form-item label="时长">
              <el-row><el-input style="margin-bottom: 5px;" type="number" v-model="item.itemTime" placeholder="课程时长，单位为秒" readonly="true"/></el-row>
            </el-form-item>

            <el-form-item label="封面">
              <el-row>
                <el-input type="hidden" v-model="item.cover" placeholder="请输入封面" />
                <ImageUpload v-model="item.cover" :data={type:6} :dis="true" :isShowTip="false" :limit="1" apiUrl="/common/uploadImg" />
              </el-row>
            </el-form-item>

            <el-row v-for="(item2, index2) in item.dayList">
              <el-form-item label="二级标题">
                <el-input type="hidden" v-model="item2.id" />
                <el-input v-model="item2.title" style="margin-bottom: 5px; width: 80%;" placeholder="请输入二级标题"  readonly="true"/>
                <el-row v-for="(item3, index3) in item2.lessonList">
                  <el-form-item label="视频">
                    <el-select v-model="item3.lessonId" placeholder="请选择课程" clearable style="width: 160px; margin-bottom: 8px;" :disabled="true" >
                      <el-option v-for="dict in lessonList" :key="dict.value" :label="dict.label" :value="dict.value" />
                    </el-select>
                  </el-form-item>
                </el-row>
              </el-form-item>
            </el-row>

          </el-row>
        </el-form-item>

        <el-form-item label="简单描述" prop="desc">
          <el-input v-model="form.desc" type="textarea" :autosize="{ minRows: 4, maxRows: 6 }" placeholder="请输入内容" readonly="true" />
        </el-form-item>
        <el-form-item label="禁忌人群" prop="prohibition">
          <el-input v-model="form.prohibition" type="textarea" :autosize="{ minRows: 4, maxRows: 6 }"
            placeholder="请输入内容" readonly="true" />
        </el-form-item>
        <el-form-item label="注意事项" prop="attention">
          <el-input v-model="form.attention" type="textarea" :autosize="{ minRows: 4, maxRows: 6 }"
            placeholder="请输入内容" readonly="true" />
        </el-form-item>
        
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Record">
import { listRecord, getRecord, delRecord, addRecord, updateRecord, getWeekPrescription, getPointPrescription, listAllPoint, listAllWeek } from "@/api/mobile/userprescription";
import {listAllLesson} from "@/api/mobile/prescription";
import {listAllUser} from "@/api/mobile/patient";

const router = useRouter();
const { proxy } = getCurrentInstance();

const tt = reactive({
  lessonId: null,
  checkinCount: null
})


const recordList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const dialogWidth = ref("0");
const showweek = ref(false);
const showpoint = ref(false);
const showlesson = ref(false);


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    phone: null,
    nickname: null
  },
  rules: {
    userId: [
      { required: true, message: "用户不能为空", trigger: "blur" }
    ],
    week: [
      { required: true, message: "周次不能为空", trigger: "blur" }
    ],
    trainTime: [
      { required: true, message: "开始训练时间不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "类型不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);


const lessonList = ref([]);
const userList = ref([]);
const pointList = ref([]);
const weekList = ref([]);

onMounted(() => {
  listAllLesson().then(res => {
    lessonList.value = res.data.map((item) => {
      return { value: `${item.id}`, label: `${item.title}` }
    })
  })

  listAllPoint().then(res => {
    pointList.value = res.data.map((item) => {
      return { value: `${item.id}`, label: `${item.point}` }
    })
  })

  listAllUser({'keyword':''}).then(res => {
    userList.value = res.data.map((item) => {
      return { value: `${item.id}`, label: `${item.nickname}` }
    })
  })

  listAllWeek().then(res => {
    weekList.value = res.data.map((item) => {
      return { value: `${item.week}`, label: `${item.weekName}` }
    })
  })
})

const remoteMethod = (query) => {
  if (query) {
    loading.value = true
    setTimeout(() => {
      loading.value = false
      listAllUser({'keyword':query}).then(res => {
        userList.value = res.data.map((item) => {
          return { value: `${item.id}`, label: `${item.nickname}` }
        })
      })
    }, 200)
  } else {
    listAllUser({'keyword':''}).then(res => {
      userList.value = res.data.map((item) => {
        return { value: `${item.id}`, label: `${item.nickname}` }
      })
    })
  }
}


function changetype(val) {
  if (val == 1) {
    showweek.value = true;
    showpoint.value = false;
    showlesson.value = false;
  } else if (val == 2) {
    showweek.value = false;
    showpoint.value = true;
    showlesson.value = false;
  } else {
    showweek.value = false;
    showpoint.value = false;
    showlesson.value = false;
  }
}


function changeweek(val) {
  if(val != null && val != '' && val != undefined){
    //获取处方详情
    getWeekPrescription(val).then(response => {
      response.data.week = String(response.data.week);
      form.value.lessonPart = response.data.lessonPart;
      form.value.desc = response.data.desc;
      form.value.prohibition = response.data.prohibition;
      form.value.attention = response.data.attention;
    })
    showlesson.value = true;
  } else {
    let jj = reactive([{
      id: null,
      title: "",
      lessonList: [{}]
    }])
    let kk = reactive([{
      id: null,
      title: "",
      cover: "",
      itemTime: null,
      dayList: jj
    }])
    form.value.lessonPart = kk;
    showlesson.value = false;
  }
}


function changepoint(val) {
  if(val != null && val != '' && val != undefined){
    //获取处方详情
    getPointPrescription(val).then(response => {
      response.data.week = String(response.data.week);
      form.value.lessonPart = response.data.lessonPart;
      form.value.desc = response.data.desc;
      form.value.prohibition = response.data.prohibition;
      form.value.attention = response.data.attention;
    })
    showlesson.value = true;
  } else {
    let jj = reactive([{
      id: null,
      title: "",
      lessonList: [{}]
    }])
    let kk = reactive([{
      id: null,
      title: "",
      cover: "",
      itemTime: null,
      dayList: jj
    }])
    form.value.lessonPart = kk;
    showlesson.value = false;
  }
}




/** 查询推荐课程记录列表 */
function getList() {
  loading.value = true;
  listRecord(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
    recordList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  showweek.value = false;
  showpoint.value = false;
  showlesson.value = false;

  let jj = reactive([{
    id: null,
    title: "",
    lessonList: [{}]
  }])
  let kk = reactive([{
    id: null,
    title: "",
    cover: "",
    itemTime: null,
    dayList: jj
  }])

  form.value = {
    id: null,
    userId: null,
    type: null,
    weekType: null,
    pointId: null,
    desc: null,
    prohibition: null,
    attention: null,
    week: null,
    trainTime: null,
    lessonPart: kk
  };
  proxy.resetForm("recordRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = null;
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户运动处方";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getRecord(_id).then(response => {
    response.data.userId = String(response.data.userId);
    // for (var i = 0; i < response.data.lessons.length; i++) {
    //   response.data.lessons[i].lessonId = String(response.data.lessons[i].lessonId);
    // }
    // response.data.lessonId = String(response.data.lessonId);
    form.value = response.data;
    form.value.type = String(form.value.type);
    if (form.value.type == 1) {
      form.value.weekType = String(form.value.weekType);
      showweek.value = true;
      showpoint.value = false;
      showlesson.value = true;
    } else if (form.value.type == 2) {
      form.value.pointId = String(form.value.pointId);
      showweek.value = false;
      showpoint.value = true;
      showlesson.value = true;
    } else {
      showweek.value = false;
      showpoint.value = false;
      showlesson.value = false;
    }
    open.value = true;
    title.value = "修改用户运动处方";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["recordRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除数据项？').then(function () {
    return delRecord(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('mobile/userprescription/export', {
    ...queryParams.value
  }, `record_${new Date().getTime()}.xlsx`)
}

function handleCheckinList(row) {
  const id = row.id
  router.push("/mobile/checkin/list/" + id);
}

function setDialogWidth() {
  var val = document.body.clientWidth
  const def = 500 // 默认宽度
  if (val < def) {
    dialogWidth.value = '100%'


  } else {
    dialogWidth.value = def + 'px'
  }
}

onMounted(() => {
  window.onresize = () => {
    return (() => {
      setDialogWidth()
    })()
  }
})

getList();
setDialogWidth();
</script>
